import request from '@/utils/request'
import type {
  PermissionDTO,
  PermissionQueryRequest,
  PageResponse,
  ApiResponse
} from '@/types/api'

// 权限管理API
export const permissionApi = {
  // 创建权限
  createPermission: (data: PermissionDTO): Promise<ApiResponse<PermissionDTO>> => {
    return request.post('/permissions', data)
  },

  // 更新权限
  updatePermission: (permissionId: string, data: PermissionDTO): Promise<ApiResponse<PermissionDTO>> => {
    return request.put(`/permissions/${permissionId}`, data)
  },

  // 获取权限详情
  getPermission: (permissionId: string): Promise<ApiResponse<PermissionDTO>> => {
    return request.get(`/permissions/${permissionId}`)
  },

  // 删除权限
  deletePermission: (permissionId: string): Promise<ApiResponse<void>> => {
    return request.delete(`/permissions/${permissionId}`)
  },

  // 分页查询权限
  queryPermissions: (params: PermissionQueryRequest): Promise<ApiResponse<PageResponse<PermissionDTO>>> => {
    return request.get('/permissions', { params })
  },

  // 获取所有权限
  getAllPermissions: (): Promise<ApiResponse<PermissionDTO[]>> => {
    return request.get('/permissions/all')
  },

  // 根据类型获取权限
  getPermissionsByType: (permissionType: string): Promise<ApiResponse<PermissionDTO[]>> => {
    return request.get(`/permissions/type/${permissionType}`)
  },

  // 获取权限树
  getPermissionTree: (): Promise<ApiResponse<PermissionDTO[]>> => {
    return request.get('/permissions/tree')
  },

  // 获取菜单权限映射（用于按菜单分组显示）
  getMenuPermissionMap: (): Promise<ApiResponse<Record<string, PermissionDTO[]>>> => {
    return request.get('/permissions/menu-permission-map')
  },

  // 获取子权限
  getChildPermissions: (permissionId: string): Promise<ApiResponse<PermissionDTO[]>> => {
    return request.get(`/permissions/${permissionId}/children`)
  },

  // 更新权限状态
  updatePermissionStatus: (permissionId: string, status: number): Promise<ApiResponse<void>> => {
    return request.put(`/permissions/${permissionId}/status`, null, {
      params: { status }
    })
  },

  // 获取权限关联的角色
  getPermissionRoles: (permissionId: string): Promise<ApiResponse<string[]>> => {
    return request.get(`/permissions/${permissionId}/roles`)
  },

  // 获取权限关联的用户
  getPermissionUsers: (permissionId: string): Promise<ApiResponse<string[]>> => {
    return request.get(`/permissions/${permissionId}/users`)
  },

  // 获取权限统计信息
  getPermissionStatistics: (): Promise<ApiResponse<{
    totalPermissions: number
    enabledPermissions: number
    disabledPermissions: number
    operationPermissions: number
    resourcePermissions: number
    apiPermissions: number
  }>> => {
    return request.get('/permissions/statistics')
  }
}

export default permissionApi
